<form lay-filter="addTemporaryForm" class="layui-form open-form">
  <div class="open-model" id="warehouseStorageRecordFormByAdd">
    <div class="open-auto">
      <input name="id" type="hidden" />

      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px"><span style="color: red">*</span>入库仓库</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <select
                    id="warehouseFactoryAdministrationId"
                    name="warehouseFactoryAdministrationId"
                    lay-filter="warehouseFactoryAdministrationId"
                    lay-search
                    lay-verify="required"
                    required></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px"><span style="color: red">*</span>选择客户</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <select id="customerId" name="customerId" lay-filter="customerId"
                    lay-verify="required" required></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px"><span style="color: red">*</span>联系人</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="hidden" id="contactId" name="contactId"/>
            <div id="len2" style="display: none">
              <input type="text" name="contactName2" disabled id="contactName2" placeholder="请选择联系人" class="layui-input" />
              <input type="hidden" id="contact" name="contactName" lay-filter="contactName"/>
            </div>
            <div id="len1">
              <select
                      id="contactName"
                      name="contactName"
                      lay-filter="contactName"
                      lay-verify="required" required
              ></select>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">关联入驻合同</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="contractCode" disabled id="contractCode" placeholder="请选择入驻合同" class="layui-input" />
            <input type="hidden" id="contractId" name="contractId"/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px"><span style="color: red">*</span>物流方式</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <select id="transportModeId" name="transportModeId" lay-filter="transportModeId"
                    lay-verify="required" required></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">物流公司</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <select id="transportCompanyId" name="transportCompanyId" lay-filter="transportCompanyId"
                    ></select>
          </div>
        </div>
      </div>
      <!--            <div class="layui-col-xs3">-->
      <!--                <div class="layui-form-item">-->
      <!--                    <label class="layui-form-label" style="width: 100px">会员开始日期</label>-->
      <!--                    <div class="layui-input-block" style="margin-left: 130px">-->
      <!--                        <input type="text" name="computerPracticeCode" id="computerPracticeCode" class="layui-input" disabled />-->
      <!--                    </div>-->
      <!--                </div>-->
      <!--            </div>-->
      <!--            <div class="layui-col-xs3">-->
      <!--                <div class="layui-form-item">-->
      <!--                    <label class="layui-form-label" style="width: 100px">会员结束时间</label>-->
      <!--                    <div class="layui-input-block" style="margin-left: 130px">-->
      <!--                        <input type="text" name="schedulingPlanDetailCode" id="schedulingPlanDetailCode" class="layui-input" disabled />-->
      <!--                    </div>-->
      <!--                </div>-->
      <!--            </div>-->
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px"><span style="color: red">*</span>运单号</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="waybill" id="waybill" class="layui-input" lay-verify="required" required />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">车牌号</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="plateNo" id="plateNo" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">司机</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="driverName" id="driverName" class="layui-input"   />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">司机电话</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="driverPhone" id="driverPhone" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">数据来源</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="hidden" id="source" name="source" value="2"/>
            <input type="text" name="sourceName" id="sourceName" value="管理后台" class="layui-input" disabled />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">客户级别</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="hidden" id="customerLevelId" name="customerLevelId" value="1"/>
            <input type="text" name="customerLevelName" id="customerLevelName"  class="layui-input" disabled />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div>
          <div class="layui-btn" id="addProduct" style="margin-top: 10px">新增货物</div>
          <div id="productList">
            <table class="layui-table" id="purchaseSignTaskProductTable" lay-filter="purchaseSignTaskProductTable"></table>
          </div>
        </div>
      </div>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="addTemporaryFormSubmit" type="button" lay-submit>提交</button>
    </div>
  </div>
</form>
<script type="text/html" id="purchaseSignTaskProductTableBar">
  <!--    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="edit">入库</a>-->
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">移除</a>
</script>
<script>
  layui.use(["form", "table", "laydate", "layedit", "laydate"], async function () {
    $ = layui.jquery;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var upload = layui.upload;
    var config = layui.config;
    var laytpl = layui.laytpl;
    var warehouseAreaList = [];

    var stamp= new Date().getTime() + 8 * 60 * 60 * 1000;
    var beijingTime = new Date(stamp).toISOString().replace(/T/, '').replace(/-/g, '').replace(/:/g, '').replace(/\..+/, '').substring(0, 14);
    $("#waybill").val(beijingTime);
    // 运输方式
    admin.reqSync(
            "enterprise/dict/admin/dictLabel/select?dictType=transport_mode",
            {},
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                loadSelectHtml(res.data, "请选择运输方式", "transportModeId", 3);
              }
            },
            "GET"
    );
    // 物流公司
    admin.reqSync(
            "enterprise/invoicing/admin/transportCompany/list",
            {limit: 9999},
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                loadSelectHtml(res.data, "请选择物流公司", "transportCompanyId");
              }
            },
            "GET"
    );
    /*入库仓库*/
    admin.reqSync(
            "warehouse/warehouse/admin/administration/list",
            {limit: 9999},
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                loadSelectHtml(res.data, "请选择入库仓库", "warehouseFactoryAdministrationId");
              }
            },
            "GET"
    );
    var factoryId=''
    //入库仓库选择
    form.on("select(warehouseFactoryAdministrationId)", function (data) {
      if (data.value === "") {
      } else {
        console.log(data,"111111")
        factoryId=data.value
        admin.reqSync(
                "warehouse/warehouse/settled/findAllContactByFactoryId",
                {factoryId: data.value, warehouseCustomerId: ''},
                function (res) {
                  layer.closeAll("loading");
                  if (res.code == 200) {
                    // $("#customerId").val(data.value);
                    loadSelectHtml(res.data, "请选客户信息", "customerId", 1);
                  }
                },
                "GET"
        );
      }
    });
    /*客户信息选择出来联系人*/
    form.on("select(customerId)", function (data) {
      if (data.value === "") {
      } else {
        let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr("data"));
        $("#customerLevelName").val('普通客户');
        admin.reqSync(
                "warehouse/warehouse/settled/findAllContactByFactoryId",
                {factoryId: factoryId, warehouseCustomerId: data.value},
                function (res) {
                  layer.closeAll("loading");
                  if (res.code == 200) {
                    // $("#customerId").val(data.value);
                    let num=1
                    res.data.map(item=>{
                      item.valueId=item.contactId+num
                      num++
                    })
                    if(res.data.length === 1){
                      let obj=res.data[0]
                      $("#len2").show()
                      $("#len1").hide()
                      $("#contactName2").val(obj.contactName)
                      $("#contact").val(obj.valueId)
                      $("#contractCode").val(obj.contractCode);
                      $("#contactId").val(obj.contactId);
                      $("#contractId").val(obj.contractId);
                    }else{
                      $("#len2").hide()
                      $("#len1").show()
                      loadSelectHtml(res.data, "请选联系人", "contactName",6);
                    }
                  }
                },
                "GET"
        );
      }
    });
    /*选择联系人之后关联出来的合同号*/
    form.on("select(contactName)", function (data) {
      if (data.value === "") {
      } else {
        let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr("data"));
        $("#contractCode").val(dataObj.contractCode);
        $("#contactId").val(dataObj.contactId);
        $("#contractId").val(dataObj.contractId);
      }
    });

    const productProducer = await admin.reqPro('warehouse/warehouse/admin/productProducer/list', {limit: 99999,});
    const productProducerList=productProducer.data
    const productVariety = await admin.reqPro('warehouse/warehouse/admin/productVariety/list', {limit: 99999,});
    const productVarietyList=productVariety.data
    const productMark = await admin.reqPro('warehouse/warehouse/admin/productMark/list', {limit: 99999,});
    const productMarkList=productMark.data
    const productUnit = await admin.reqPro('enterprise/product/admin/productUnit/list', {limit: 99999,});
    const productUnitList=productUnit.data
    const typeList=[
      {
        val:1,name:'普通物资'
      },{
        val:2,name:'加工预料'
      },{
        val:3,name:'加工原料'
      },{
        val:4,name:'加工成品'
      }
    ]
    var insTb = table.render({
      elem: "#purchaseSignTaskProductTable",
      data: [],
      page: false,
      limit: 99999,
      cellMinWidth: 100,
      height: 360,
      cols: [
        [
          { type: "numbers", title: "序号", height: 50 },
          {
            field: "userBundleDetail",
            align: "center",
            title: "客户捆包号",
            templet: admin.setTableInput("userBundleDetail", false, "userBundleDetail")
          },
          {
            field: "type",
            align: "center",
            title: "物资类型",
            templet: admin.setTableSelect("type",
                    typeList.map((v) => {
                      return {
                        label: v.name,
                        value: v.val
                      };
                    }), false, "type")
          },

          {
            field: "productProducerId",
            align: "center",
            title: "产地/厂家",
            templet: admin.setTableSelect("productProducerId",
                    productProducerList.map((v) => {
                      return {
                        label: v.producerName,
                        value: v.id
                      };
                    }), false, "productProducerId")
          },
          {
            field: "productVarietyId",
            align: "center",
            title: "品种",
            templet: admin.setTableSelect("productVarietyId",
                    productVarietyList.map((v) => {
                      return {
                        label: v.varietyName,
                        value: v.id
                      };
                    }), false, "productVarietyId")
          },{
          field: "productMarkId",
          align: "center",
          title: "钢种/牌号",
          templet: admin.setTableSelect("productMarkId",
                  productMarkList.map((v) => {
                    return {
                      label: v.markName,
                      value: v.id
                    };
                  }), false, "productMarkId")
        },{
          field: "productMainUnitId",
          align: "center",
          title: "数量单位",
          templet: admin.setTableSelect("productMainUnitId",
                  productUnitList.map((v) => {
                    return {
                      label: v.name,
                      value: v.id
                    };
                  }), false, "productMainUnitId")
        },
          {
            field: "quantity",
            align: "center",
            title: "数量",
            templet: admin.setTableInput("quantity", true, "quantity")
          },


          {
            field: "width",
            align: "center",
            title: "宽度",
            templet: admin.setTableInput("width", false, "width")
          },
          {
            field: "length",
            align: "center",
            title: "长度",
            templet: admin.setTableInput("length", false, "length")
          },
          {
            field: "thickness",
            align: "center",
            title: "厚度",
            templet: admin.setTableInput("thickness", false, "thickness")
          },
          {
            field: "productSpecCode",
            align: "center",
            title: "规格码",
            templet: admin.setTableInput("productSpecCode", false, "productSpecCode")
          },
          {
          field: "grossWeight",
          align: "center",
          title: "毛重(吨)",
          templet: admin.setTableInput("grossWeight", false, "grossWeight")
        },{
          field: "netWeight",
          align: "center",
          title: "净重(吨 )",
          templet: admin.setTableInput("netWeight", false, "netWeight")
        },
          // { field: "inventorySum", align: "center", title: "当前库存" },

          { align: "center", toolbar: "#purchaseSignTaskProductTableBar", title: "操作", width: 100 }
        ]
      ],
      done: () => {
        admin.tableInputChange("purchaseSignTaskProductTable");
        admin.tableInputChangeByClass("purchaseSignTaskProductTable", "width", (index, value, tableData, field, tableId) => {
          calculate(index, tableData);
        });
        admin.tableInputChangeByClass("purchaseSignTaskProductTable", "length", (index, value, tableData, field, tableId) => {
          calculate(index, tableData);
        });
        admin.tableInputChangeByClass("purchaseSignTaskProductTable", "thickness", (index, value, tableData, field, tableId) => {
          calculate(index, tableData);
        });
        function calculate(index, tableData, type) {
          let width = tableData[index].width || null; //
          let length = tableData[index].length || null; //
          let thickness = tableData[index].thickness || null; //
          let productSpecCode=thickness+'*'+width+'*'+length
          tableData[index].productSpecCode = productSpecCode;
          let html='<input name="productSpecCode" class="layui-input editable-input thickness" type="text" value="' + tableData[index].productSpecCode + '" data-field="productSpecCode"  lay-text="规格吗"/>'
          admin.setTableColHtml("purchaseSignTaskProductTable", index, "productSpecCode", html);
        }
        admin.tableSelectChange("purchaseSignTaskProductTable",'type');
        admin.tableSelectChange("purchaseSignTaskProductTable",'productSpecCode');
        admin.tableSelectChange("purchaseSignTaskProductTable",'productProducerId');
        admin.tableSelectChange("purchaseSignTaskProductTable",'productVarietyId');
        admin.tableSelectChange("purchaseSignTaskProductTable",'productMarkId');
        admin.tableSelectChange("purchaseSignTaskProductTable",'productMainUnitId');
      }
    });

    $("#warehouseStorageRecordFormByAdd .layui-table-body").css("overflow", "visible");
    $("#warehouseStorageRecordFormByAdd .layui-table-box").css("overflow", "visible");
    $("#warehouseStorageRecordFormByAdd .layui-table-view").css("overflow", "visible");

    table.on("tool(purchaseSignTaskProductTable)", function (obj) {
      var data = obj.data;

      let list = table.cache['purchaseSignTaskProductTable'];
      if (obj.event === "del") {
        list.splice(obj.data.index, 1);
        table.reload('purchaseSignTaskProductTable', {
          data: list, // 设置新的数据
        });
      }
    });
    $("#addProduct").click(function () {
      // let warehouseQualityTestingId = $("#warehouseQualityTestingId").val();
      // let warehouseProductId = $("#warehouseProductId").val();
      let data = table.cache["purchaseSignTaskProductTable"];
      data.unshift({
        userBundleDetail: "",
        type: "",
        productSpecCode: "",
        productProducerId:'',
        productVarietyId:'',
        productMarkId:'',
        productMainUnitId:'',
        quantity:1,
        grossWeight:'',
        netWeight:''
      });
      table.reload("purchaseSignTaskProductTable", {
        data: data
      });
    });

    form.on("submit(addTemporaryFormSubmit)", function (d) {
      const formData = {...d.field};
      formData.orderId=formData.contractId
      formData.orderCode=formData.contractCode
      formData.warehouseShipmentOrderDetail = table.cache["purchaseSignTaskProductTable"];
      let totalWeight=0
      let totalQuantity=0
      if($("#len2").is(":visible") && $("#contact").val()!=='' && $("#contact").val()!==undefined){
        formData.contactName=$("#contact").val()
      }
      console.log(formData,"2222")
      if(formData.warehouseShipmentOrderDetail.length==0){
        layer.msg("请添加货物数据", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.userBundleDetail == '')) {
        layer.msg("请填写客户捆包号", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.type == '')) {
        layer.msg("请选择物资类型", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.productProducerId == '')) {
        layer.msg("请选择产地/厂家", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.productVarietyId == '')) {
        layer.msg("请选择品种", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.productMarkId == '')) {
        layer.msg("请选择钢种/牌号", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.productMainUnitId == '')) {
        layer.msg("请选择数量单位", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.width == '')) {
        layer.msg("请填写宽度", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.length == '')) {
        layer.msg("请填写长度", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.thickness == '')) {
        layer.msg("请填写厚度", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.quantity == ''|| !Number(item.quantity)||Number(item.quantity) <= 0 )) {
        layer.msg("请填写数量且不能为非数字", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.grossWeight == ''|| !Number(item.grossWeight)||Number(item.grossWeight) <= 0 )) {
        layer.msg("请填写毛重(吨)且不能为非数字", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseShipmentOrderDetail.some(item =>item.netWeight == ''|| !Number(item.netWeight)||Number(item.netWeight) <= 0 )) {
        layer.msg("请填写净重(吨 )且不能为非数字", {icon: 2, time: 1000});
        return false;
      }
      formData.warehouseShipmentOrderDetail.map(item=>{
        totalQuantity+=Number(item.quantity)
        totalWeight+=Number(item.netWeight)
      })
      formData.totalQuantity=totalQuantity
      formData.totalWeight=totalWeight
      layer.load(2);
      admin.req(
              "warehouse/warehouse/shipmentOrder/add",
              JSON.stringify(formData),
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg(res.msg, {icon: 1});
                  table.reload("warehouseShipmentOrderTable", {});
                  layer.closeAll("page");
                } else {
                  layer.msg(res.msg, {icon: 2});
                }
              },
              "POST",
              false,
              "application/json"
      );
    });

    // option渲染
    function loadSelectHtml(data, tips, htmltarget, type) {
      let html = " <option value>" + tips + "</option>";
      if (!data || data == null) {
        return;
      }
      for (let i = 0; i < data.length; i++) {
        if (type == 1) {
          html += `<option value='${data[i].warehouseCustomerId}' id='${data[i].warehouseCustomerId}' data='${JSON.stringify(data[i])}' >${data[i].customerName}</option>`;
        } else if (type == 2) {
          html += `<option value='${data[i].orderCode}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].orderCode}</option>`;
        } else if (type == 3) {
          html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].labelName}</option>`;
        } else if (type == 4) {
          html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' >${data[i].shipmentOrderCode}</option>`;
        }else if (type == 5) {
          html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' >${data[i].contactName}</option>`;
        } else if (type == 6) {
          html += `<option value='${data[i].valueId}' id='${data[i].valueId}' data='${JSON.stringify(data[i])}' >${data[i].contactName}</option>`;
        } else {
          html += `<option value='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].name}</option>`;
        }
      }

      $("form select[name='" + htmltarget + "']").html(html);
      form.render("select");
    }
  });
</script>
<style>
  #warehouseStorageRecordFormByAdd .layui-table-cell {
    overflow: visible !important;
  }
</style>
